package com.example.manage_dzensaas.config;

import com.example.manage_dzensaas.service.CardInvokeService;
import org.noear.folkmq.FolkMQ;
import org.noear.folkmq.client.MqClient;
import org.noear.folkmq.client.MqConsumeHandler;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * folkMQ配置
 * @author wangzhiqi
 */
@Configuration
public class FolkMqConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(FolkMqConfig.class);

    @Bean
    public MqClient initClient(@Inject("${folkmq.server}") String serverUrl,
                               @Inject("${folkmq.consumerGroup}") String consumerGroup,
                               @Inject("${folkmq.namespace}") String namespace,
                               @Inject("${folkmq.ak}") String ak,
                               @Inject("${folkmq.sk}") String sk,
                               @Inject Map<String, MqConsumeHandler> subscriptionMap) throws IOException {
        LOGGER.info("初始化MqClient {} - {} - {}", serverUrl, consumerGroup, namespace);
        //构建客户端
        MqClient client = FolkMQ.createClient(serverUrl)
                .namespaceAs(namespace)
                .nameAs(consumerGroup)
                .config(c -> c
                        .metaPut("ak", ak)
                        .metaPut("sk", sk)
                )
                .connect();

        //订阅
        for (Map.Entry<String, MqConsumeHandler> subscription : subscriptionMap.entrySet()) {
            LOGGER.info("订阅：{} 分组：{}", subscription.getKey(), consumerGroup);
            client.subscribe(subscription.getKey(), subscription.getValue());
        }

        return client;
    }
}
